const express = require('express');
const router = express.Router();
const Goods = require('../models/Goods');
const Category = require('../models/Category');

// 获取商品分类数据
router.get('/findCategoryTree', async (req, res) => {
  try {
    const categories = await Category.find().sort({ sort: 1 });
    const tree = buildCategoryTree(categories);
    res.json({
      code: 200,
      message: '成功',
      data: tree
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取分类失败',
      data: null
    });
  }
});

// 获取商品列表
router.get('/list', async (req, res) => {
  try {
    const { categoryId, keyword, page = 1, pageSize = 10 } = req.query;
    const query = { status: 1 };
    
    if (categoryId) {
      query.category = categoryId;
    }
    
    if (keyword) {
      query.name = new RegExp(keyword, 'i');
    }

    const total = await Goods.countDocuments(query);
    const goods = await Goods.find(query)
      .populate('category')
      .sort({ createdAt: -1 })
      .skip((page - 1) * pageSize)
      .limit(parseInt(pageSize));

    res.json({
      code: 200,
      message: '成功',
      data: {
        total,
        list: goods
      }
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品列表失败',
      data: null
    });
  }
});

// 获取商品详情
router.get('/item/:id', async (req, res) => {
  try {
    const goods = await Goods.findById(req.params.id)
      .populate('category');
    
    if (!goods) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '成功',
      data: goods
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品详情失败',
      data: null
    });
  }
});

// 获取商品评价
router.get('/comment/:id', async (req, res) => {
  try {
    const comments = await Comment.find({ goods: req.params.id })
      .populate('user', 'nickname avatar')
      .sort({ createdAt: -1 });
    
    res.json({
      code: 200,
      message: '成功',
      data: comments
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品评价失败',
      data: null
    });
  }
});

// 搜索商品
router.get('/search', async (req, res) => {
  try {
    const { keyword } = req.query;
    const goods = await Goods.find({
      status: 1,
      name: new RegExp(keyword, 'i')
    })
    .populate('category')
    .limit(20);

    res.json({
      code: 200,
      message: '成功',
      data: goods
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '搜索商品失败',
      data: null
    });
  }
});

// 获取商品规格
router.get('/item/specs/:id', async (req, res) => {
  try {
    const goods = await Goods.findById(req.params.id);
    if (!goods) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '成功',
      data: goods.specs
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品规格失败',
      data: null
    });
  }
});

// 获取商品价格
router.get('/item/price/:id', async (req, res) => {
  try {
    const goods = await Goods.findById(req.params.id);
    if (!goods) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '成功',
      data: {
        price: goods.price,
        originalPrice: goods.originalPrice
      }
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品价格失败',
      data: null
    });
  }
});

// 获取商品库存
router.get('/item/stock/:id', async (req, res) => {
  try {
    const goods = await Goods.findById(req.params.id);
    if (!goods) {
      return res.status(404).json({
        code: 404,
        message: '商品不存在',
        data: null
      });
    }

    res.json({
      code: 200,
      message: '成功',
      data: {
        stock: goods.stock
      }
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: '获取商品库存失败',
      data: null
    });
  }
});

// 构建分类树
function buildCategoryTree(categories, parentId = null) {
  return categories
    .filter(category => String(category.parent) === String(parentId))
    .map(category => ({
      ...category.toObject(),
      children: buildCategoryTree(categories, category._id)
    }));
}

module.exports = router; 